import { adminList, appUserTree, appUserTreeAdd, appUserTreeDelete, appUserTreeEdit,userProfileDisable, userProfileList, userProfileRemove, userProfileResetPassword, userProfileStatus } from "@/services/userProfile";
import { Button, Col, DatePicker, Form, Input, Modal, Row, Select, Table, message,Layout,Spin,Pagination } from "antd";
import React from "react";
import { ButtonGroup, MoreOption, TreeShape } from "@/utils/CommonComponent";
import moment from "moment";
import UpdateUser from "./updateUser";
import tableDataCheck from "@/utils/isBackPrevPage";
import BatchModal from "./batchModal";

const { Header, Footer, Sider, Content } = Layout;

class AdminUser extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      optNode:{},
      currentNode:{},
      treeData:[],
      treeLoading:false,
      expandedKeys:[],

      current:1,
      size:10,
      list:[],
      total:0,
      loading:false,

      addMenuList:[
        {
          key:'add',
          name:"创建账号"
        },
        {
          key:"import",
          name:"导入用户"
        }
      ],

      optMenuList:[
        {
          key:'agree',
          name:"批量通过"
        },
        {
          key:'refuse',
          name:"批量拒绝"
        },
        {
          key:'stop',
          name:"批量停用"
        },
        {
          key:'start',
          name:"批量启用"
        },
        {
          key:'delete',
          name:"批量删除"
        },
      ],
      selectedRowKeys:[],
      selectedRows:[]
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  doSearch = (current,size) => {
    this.setState({
      current,size
    },() => {
      this.getTableData()
    })
  }

  getTableData = () => {
    this.setState({
      loading:true
    },async () => {
      const { current,size,currentNode} = this.state;
      const { applicationId } = this.props;
      const info = this.props.form.getFieldsValue()
      let obj = {
        current,
        size,
        applicationId,
        search:info.search,
        startTime:info.time && info.time[0] ? moment(info.time[0]).format("YYYY-MM-DD") : '',
        endTime:info.time && info.time[1] ? moment(info.time[1]).format("YYYY-MM-DD") : '',
        status:info.status
      }
      const res = await adminList(obj)
      this.setState({
        list:res.records,
        total:res.total,
        loading:false,
        selectedRowKeys:[]
      })
    })
  }

  moreMenuClick = e => {
    const { selectedRowKeys } = this.state;
    switch(e.key){
      case 'add':
        this.openAddModal(null)
        break;
      case 'import':
        this.BatchModal.openModal()
        break;
      case 'agree':
        this.changeStatus(selectedRowKeys,0)
        break;
      case 'refuse':
        this.changeStatus(selectedRowKeys,3)
        break;
      case 'stop':
        this.changeStatus(selectedRowKeys,1)
        break;
      case 'start':
        this.changeStatus(selectedRowKeys,0)
        break;
      case 'delete':
        this.removeConfirm(selectedRowKeys)
        break;

    }
  }

  openAddModal = (row) => {
    this.UpdateUser.initData(row)
  }

  removeConfirm = idList => {
    if(idList.lenght == 0){
      message.error("请选择需要操作的数据")
      return false
    }
    const that = this
    Modal.confirm({
      title: "是否确定删除？",
      okText: "确定",
      cancelText: "取消",
      okType: "danger",
      onOk() {
        that.doRemove(idList)
      }
    })
  }

  doRemove = async idList => {
    const res = await userProfileRemove({ idList })
    const { list, current, size } = this.state;
    const newCurrent = tableDataCheck(list, current, idList);
    this.doSearch(newCurrent, size)
    message.info(res.message)
  }

  resetPassword = async id => {
    const res = await userProfileResetPassword({ id })
    message.info(res.message)
  }

  changeStatus = async (idList, status) => {
    if(idList.length == 0){
      message.error("请选择需要操作的数据")
      return false
    }
    const res = await userProfileStatus({ idList, status })
    message.info(res.message)
    this.getTableData()
  }

  render(){
    const {
      optNode,
      currentNode,
      treeData,
      treeLoading,
      expandedKeys,
      current,
      size,
      total,
      list,
      loading,
      addMenuList,
      optMenuList,
      selectedRowKeys
     } = this.state;
     const { form: { getFieldDecorator }, applicationId } = this.props;
     const columns = [
      {
        title: "序号",
        dataIndex: "index",
        width: 60,
        render(text, row, index) {
          return (current - 1) * size + (index + 1)
        }
      },
      {
        title: "姓名",
        dataIndex: "name",
        width: 100
      },
      {
        title: "账号",
        dataIndex: "phone",
        width: 100
      },
      {
        title: "手机号",
        dataIndex: "mobilePhone",
        width: 100
      },
      {
        title: "拦截次数",
        dataIndex: "num",
        width: 100
      },
      {
        title: "注册时间",
        dataIndex: "createTime",
        width: 100,
        render: time => {
          return time ? moment(time).format("YYYY-MM-DD HH:mm:ss") : ''
        }
      },
      {
        title: "最新登录时间",
        dataIndex: "lastLoginTime",
        width: 110,
        render: time => {
          return time ? moment(time).format("YYYY-MM-DD HH:mm:ss") : ''
        }
      },
      {
        title: "状态",
        dataIndex: "status",
        width: 80,
        render(type) {
          switch (type) {
            case 0:
              return <span style={{ color: '#52c41a' }}>正常</span>
            case 1:
              return <span style={{ color: "red" }}>禁用</span>
            case 2:
              return <span style={{ color: "#3e5bff" }}>申请中</span>
            case 3:
              return <span style={{ color: "red" }}>拒绝</span>
          }
        }
      },
      {
        title: "操作",
        width: 150,
        render: (text, row) => {
          return <div>
            {
              row.status == 0 ? (
                <ButtonGroup 
                    title="停用"
                    group="stop-table"
                    handleClick={() => this.changeStatus([row.id], 1)}
                  />
              ) : ''
            }
            {
              row.status == 1 ? (
                <ButtonGroup 
                    title="启用"
                    group="start-table"
                    handleClick={() => this.changeStatus([row.id], 0)}
                  />
              ) : ''
            }
            <ButtonGroup 
              title="恢复默认密码"
              group="reset-table"
              handleClick={() => this.resetPassword(row.id)}
            />
          </div>
        }
      },
    ]
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRowKeys,
          selectedRows
        })
      },
      selectedRowKeys
    };

     return (
      <Layout style={{height:"100%"}}>
        <Content style={{background:"#ffffff",borderRadius:"0 6px 6px 0",padding:10}}>
          <div className="topOptionBox">
            <div className="topOptionBox-left">
              <Form layout="inline">
                <Form.Item>
                  {
                    getFieldDecorator("status")(
                      <Select style={{width:100}} onChange={() => this.doSearch(1,size)} placeholder='状态'>
                        <Select.Option value={null}>全部</Select.Option>
                        <Select.Option value={0}>正常</Select.Option>
                        <Select.Option value={1}>停用</Select.Option>
                      </Select>
                    )
                  }
                </Form.Item>
                <Form.Item>
                  {
                    getFieldDecorator("time")(
                      <DatePicker.RangePicker style={{width:250}} onChange={() => this.doSearch(1,size)} />
                    )
                  }
                </Form.Item>
                <Form.Item>
                  {
                    getFieldDecorator("search", { initialValue: "" })(
                      <Input.Search placeholder="账号/姓名" onSearch={() => this.doSearch(1, size)} />
                    )
                  }
                </Form.Item>
                
              </Form>
            </div>
            <div className="topOptionBox-right">
              <Button type="primary" onClick={() => this.moreMenuClick({key:'add'})} style={{marginRight:8}}>创建账号</Button>
              <Button type="danger" onClick={() => this.moreMenuClick({key:'delete'})}>删除账号</Button>
            </div>
          </div>

          <Table 
            dataSource={list}
            loading={loading}
            rowKey='id'
            pagination={false}
            scroll={{ x: "auto", y: 'calc(100vh - 380px)' }}
            columns={columns}
            rowSelection={rowSelection}
          />
          {parseInt(total) > 10 ? (
            <Pagination
              showQuickJumper
              total={total}
              current={current}
              onChange={this.doSearch}
              style={{ textAlign: 'right', marginTop: 16 }}
            />
          ) : null}

        </Content>

        <UpdateUser 
          onRef={ref => this.UpdateUser = ref} 
          applicationId={applicationId} 
          refershList={() => this.doSearch(1, size)} 
          currentNode={currentNode}
        />
        <BatchModal 
          onRef={ref => this.BatchModal = ref} 
          applicationId={applicationId} 
          refreshList={() => this.doSearch(1, size)} 
        />
      </Layout>
     )
  }
}

export default Form.create()(AdminUser)